package com.ms.controller;

import com.ms.entity.Manager;
import com.ms.entity.Organizer;
import com.ms.entity.QuaApplication;
import com.ms.service.inter.QuaApplicationService;
import com.ms.utils.ManagerContext;
import com.ms.utils.UserContext;
import com.ms.utils.SimpleTokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;

/**
 * 资格申请控制器
 * 处理举办资格申请相关接口
 */
@RestController
@RequestMapping("/quaApplication")
public class QuaApplicationController {

    @Autowired
    private QuaApplicationService quaApplicationService;

    /**
     * 1. 申请材料提交（包含文件上传）
     * 接收申请信息和文件并保存到数据库
     * 只有举办方可以提交申请，系统自动填充举办方信息
     */
    @PostMapping("/submit")
    public Map<String, Object> submitApply(HttpServletRequest request,
                                           @RequestParam(required = false) String gamesName,
                                           @RequestParam(required = false) MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 从请求头获取token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("msg", "未登录");
                return result;
            }

            // 验证token
            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Organizer)) {
                result.put("success", false);
                result.put("msg", "无权限操作，仅举办方可以提交申请");
                return result;
            }

            QuaApplication quaApplication = new QuaApplication();
            quaApplication.setGamesName(gamesName);
            
            // 处理文件上传
            if (file != null && !file.isEmpty()) {
                // 生成唯一文件名
                String originalFileName = file.getOriginalFilename();
                String extension = "";
                if (originalFileName != null && originalFileName.contains(".")) {
                    extension = originalFileName.substring(originalFileName.lastIndexOf("."));
                }
                String uniqueFileName = UUID.randomUUID().toString() + extension;
                
                // 确保目录存在
                String uploadDir = System.getProperty("user.dir") + "/src/main/resources/static/qua_app/";
                File dir = new File(uploadDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                
                // 保存文件
                Path path = Paths.get(uploadDir + uniqueFileName);
                Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
                
                // 将文件路径保存到申请材料字段
                quaApplication.setApplyMaterials("/static/qua_app/" + uniqueFileName);
            }
            
            boolean success = quaApplicationService.submitApply(token, quaApplication);
            result.put("success", success);
            result.put("msg", success ? "申请提交成功" : "申请提交失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "提交失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 2. 申请状态查询
     * 根据当前登录的用户类型返回不同的申请列表：
     * 举办方：只返回自己的申请列表
     * 管理员：返回所有申请列表，未审批的在最上方，相同状态按日期从老到新排序
     */
    @GetMapping("/status")
    public Map<String, Object> getApplyStatus(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 从请求头获取token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("msg", "未登录");
                return result;
            }

            // 验证token
            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (userObj == null) {
                result.put("success", false);
                result.put("msg", "登录已过期，请重新登录");
                return result;
            }

            // 判断用户类型
            if (userObj instanceof Organizer) {
                // 举办方查询自己的申请
                Organizer organizer = (Organizer) userObj;
                List<QuaApplication> applications = quaApplicationService.getApplyStatusByOrganizer(organizer.getOrId());
                result.put("success", true);
                result.put("data", applications);
            } else if (userObj instanceof Manager) {
                // 管理员查询所有申请，按指定规则排序
                List<QuaApplication> applications = quaApplicationService.getAllApplyStatusOrdered();
                result.put("success", true);
                result.put("data", applications);
            } else {
                result.put("success", false);
                result.put("msg", "不支持的用户类型");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "查询失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 3. 对资格申请进行审批处理
     * 管理员审核申请并更新审核结果
     * 只有管理员身份才可以操作
     * 审批通过，自动生成game
     */
    @PostMapping("/feedback")
    public Map<String, Object> feedbackApplyResult(HttpServletRequest request, @RequestBody QuaApplication quaApplication) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 从请求头获取token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("msg", "未登录");
                return result;
            }

            // 验证当前登录用户是否为管理员
            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Manager)) {
                result.put("success", false);
                result.put("msg", "权限不足，仅管理员可操作");
                return result;
            }

            boolean success = quaApplicationService.feedbackApplyResult(quaApplication);
            result.put("success", success);
            result.put("msg", success ? "审核结果已更新" : "审核结果更新失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "操作失败：" + e.getMessage());
        }
        return result;
    }
    
    /**
     * 4. 主办方撤销未审批的资格申请
     * 只有申请状态为"待审核"(0)的申请可以被撤销
     * 
     * @param request HTTP请求
     * @param quaId 资格申请ID
     * @return 撤销结果
     */
    @DeleteMapping("/cancel")
    public Map<String, Object> cancelApplication(HttpServletRequest request, @RequestParam Integer quaId) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 从请求头获取token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("msg", "未登录");
                return result;
            }

            // 验证当前登录用户是否为举办方
            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Organizer)) {
                result.put("success", false);
                result.put("msg", "权限不足，仅举办方可操作");
                return result;
            }
            
            Organizer organizer = (Organizer) userObj;
            
            // 检查申请是否存在且属于当前举办方
            QuaApplication application = quaApplicationService.getById(quaId);
            if (application == null) {
                result.put("success", false);
                result.put("msg", "申请记录不存在");
                return result;
            }
            
            // 检查是否属于当前举办方
            if (!application.getOrId().equals(organizer.getOrId())) {
                result.put("success", false);
                result.put("msg", "无权限操作其他举办方的申请");
                return result;
            }
            
            // 检查申请状态是否为待审核(0)
            if (application.getApplyStatus() != 0) {
                result.put("success", false);
                result.put("msg", "只能撤销未审批的申请");
                return result;
            }
            
            // 删除申请
            boolean success = quaApplicationService.removeById(quaId);
            result.put("success", success);
            result.put("msg", success ? "申请已撤销" : "撤销失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "操作失败：" + e.getMessage());
        }
        return result;
    }
    
    /**
     * 5. 查看申请材料详情
     * 管理员或主办方查看申请材料详情
     * 
     * @param request HTTP请求
     * @param quaId 资格申请ID
     * @return 申请材料详情
     */
    @GetMapping("/detail")
    public Map<String, Object> getApplicationDetail(HttpServletRequest request, @RequestParam Integer quaId) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 从请求头获取token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("msg", "未登录");
                return result;
            }

            // 验证当前登录用户是否为管理员或主办方
            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Manager) && !(userObj instanceof Organizer)) {
                result.put("success", false);
                result.put("msg", "权限不足，仅管理员或举办方可操作");
                return result;
            }
            
            // 获取申请详情
            QuaApplication application = quaApplicationService.getById(quaId);
            if (application == null) {
                result.put("success", false);
                result.put("msg", "申请记录不存在");
                return result;
            }
            
            // 权限检查
            if (userObj instanceof Organizer) {
                // 主办方只能查看自己的申请
                Organizer organizer = (Organizer) userObj;
                if (!application.getOrId().equals(organizer.getOrId())) {
                    result.put("success", false);
                    result.put("msg", "无权限查看其他举办方的申请");
                    return result;
                }
            }
            // 管理员可以查看所有申请，无需额外权限检查
            
            result.put("success", true);
            result.put("data", application);
            result.put("msg", "获取成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "操作失败：" + e.getMessage());
        }
        return result;
    }
}